package com.ruoyi.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.SysOssMapper;
import com.ruoyi.user.domain.bo.MyCourseBo;
import com.ruoyi.user.domain.bo.OneClassify;
import com.ruoyi.user.domain.bo.RegisterVo;
import com.ruoyi.user.uilts.JwtUtils;
import com.ruoyi.user.uilts.RegexUtils;
import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Service;
import com.ruoyi.user.domain.bo.UcenterMemberBo;
import com.ruoyi.user.domain.vo.UcenterMemberVo;
import com.ruoyi.user.domain.UcenterMember;
import com.ruoyi.user.mapper.UcenterMemberMapper;
import com.ruoyi.user.service.IUcenterMemberService;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户Service业务层处理
 *
 * @author 孟磊
 * @date 2022-08-18
 */
@RequiredArgsConstructor
@Service
public class UcenterMemberServiceImpl implements IUcenterMemberService {

    private final UcenterMemberMapper baseMapper;

    private final SysOssMapper sysOssMapper;

    /**
     * 查询用户
     */
    @Override
    public UcenterMemberVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户列表
     */
    @Override
    public TableDataInfo<UcenterMemberVo> queryPageList(UcenterMemberBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UcenterMember> lqw = buildQueryWrapper(bo);
        Page<UcenterMemberVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<UcenterMemberVo> records = result.getRecords();

        for (UcenterMemberVo record : records) {
            String avatar = record.getAvatar();
            SysOssVo sysOssVo = sysOssMapper.selectVoById(avatar);
            record.setAvatar(sysOssVo.getUrl());
        }
        result.setRecords(records);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户列表
     */
    @Override
    public List<UcenterMemberVo> queryList(UcenterMemberBo bo) {
        LambdaQueryWrapper<UcenterMember> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UcenterMember> buildQueryWrapper(UcenterMemberBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UcenterMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), UcenterMember::getMobile, bo.getMobile());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), UcenterMember::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), UcenterMember::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), UcenterMember::getAge, bo.getAge());
        lqw.eq(bo.getIsDisabled() != null, UcenterMember::getIsDisabled, bo.getIsDisabled());
        lqw.eq(bo.getCreateTime() != null, UcenterMember::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, UcenterMember::getUpdateTime, bo.getUpdateTime());
        return lqw;
    }

    /**
     * 新增用户
     */
    @Override
    public R insertByBo(UcenterMemberBo bo) {
        if (RegexUtils.isPhoneInvalid(bo.getMobile())){
            return R.fail("手机号格式错误");
        }
        UcenterMember add = BeanUtil.toBean(bo, UcenterMember.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return R.ok();
    }

    /**
     * 修改用户
     */
    @Override
    public R updateByBo(UcenterMemberBo bo) {
        String mobile = bo.getMobile();
        Long count = baseMapper.selectCount(new QueryWrapper<UcenterMember>().eq("mobile", mobile));
        if (count>2){
            return R.fail("手机号已被注册");
        }

        if (StringUtils.isNotEmpty(bo.getMail())){
            //判断邮箱是否符合格式
            if (RegexUtils.isEmailInvalid(bo.getMail())){
                return R.fail("邮箱不符合格式");
            }
        }
        if (StringUtils.isNotEmpty(bo.getPassword())){
            UcenterMemberVo ucenterMemberVo = baseMapper.selectVoById(bo.getId());
            String password = ucenterMemberVo.getPassword();
            //判断输入的原密码是否正确
            if (!password.equals(bo.getPassword())){
                return R.fail("输入的原密码不正确");
            }
            bo.setPassword(bo.getPsd());
        }
        UcenterMember update = BeanUtil.toBean(bo, UcenterMember.class);
        validEntityBeforeSave(update);
//        return baseMapper.updateById(update) > 0;
        baseMapper.updateById(update);
        return R.ok();
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UcenterMember entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R login(UcenterMemberBo bo) {

        //拿到手机号
        String mobile = bo.getMobile();
        //判断手机号密码不能为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(bo.getPassword())){
            return R.fail("手机号或密码不能为空");
        }
        //判断手机号是否注册
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(wrapper);
        if (ucenterMember == null){
            return R.fail("手机号没有注册");
        }
        //根据手机号判断密码是否正确
        if (bo.getPassword().equals(ucenterMember.getPassword())){
            String token = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
            return R.ok("登录成功",token);
        }else{
            return R.fail("密码不对");
        }

    }

    @Override
    public R register(RegisterVo ro) {
        String mobile = ro.getMobile();
        String password = ro.getPassword();
        String code = ro.getCode();
        //判断验证码是否正确
        String key = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        Object cacheObject = RedisUtils.getCacheObject(key);
        System.out.println(cacheObject);
        int i = Integer.parseInt(String.valueOf(cacheObject));
        if (code.equals(i)){
            return R.fail("验证码错误");
        }
        //判断不能为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            return R.fail("账号密码不能为空");
        }
        //拿到手机号判断是否符合格式
        if (RegexUtils.isPhoneInvalid(mobile)){
            return R.fail("手机号格式错误");
        }
        //判断手机号是否注册
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(wrapper);
        if (ucenterMember == null){
            //添加数据
            UcenterMember ucenterMember1 = new UcenterMember();
            ucenterMember1.setIsDisabled(1);
            ucenterMember1.setNickname(mobile);
            ucenterMember1.setMobile(mobile);
            ucenterMember1.setPassword(password);
            baseMapper.insert(ucenterMember1);
//        return null;
            return R.ok();
        }else {
            return R.fail("手机号被注册");
        }

    }

    @Override
    public R query() {
        List<UcenterMemberVo> ucenterMemberVos = baseMapper.selectVoList(null);
        return R.ok(ucenterMemberVos);
    }

    @Override
    public List<OneClassify> queryclassify() {
        return baseMapper.queryclassify();
    }

    @Override
    public List<OneClassify> queryTeacher() {
        return baseMapper.queryTeacher();
    }

    @Override
    public List<OneClassify> average() {
        return baseMapper.average();
    }

    @Override
    public List<OneClassify> week() {
        return baseMapper.week();
    }

    @Override
    public List<MyCourseBo> mycourse(int id) {
        return baseMapper.mycourse(id);
    }


}
